package com.example.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.admin.entity.SysJob;
import com.example.admin.mapper.SysJobMapper;
import com.example.admin.service.ISysJobService;
import com.example.publice.error.TaskException;
import com.example.publice.quartz.ScheduleConstants;
import com.example.publice.quartz.ScheduleUtils;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 定时任务调度表 服务实现类
 * </p>
 *
 * @author wangkai
 * @since 2020-09-29
 */
@Service("sysJobService")
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {

    @Autowired
    private Scheduler scheduler;


    @Override
    public boolean saveSysJob(SysJob sysJob) {
        if (sysJob.insert()) {
            if (sysJob.getStatus().equals(ScheduleConstants.Status.NORMAL.getValue())) {
                try {
                    ScheduleUtils.createScheduleJob(scheduler, sysJob);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    @Override
    public boolean updateSysJob(SysJob sysJob) {
        if (sysJob.insertOrUpdate()) {
            if (sysJob.getStatus().equals(ScheduleConstants.Status.NORMAL.getValue())) {
                try {
                    ScheduleUtils.createScheduleJob(scheduler, sysJob);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public boolean deleteSysJob(Integer[] ids) {
        QueryWrapper<SysJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("job_id", ids);
        List<SysJob> list = list(queryWrapper);
        if (list != null && list.size() > 0) {
            list.stream().filter(info -> info.getStatus().equals(ScheduleConstants.Status.NORMAL.getValue())).forEach(job -> {
                try {
                    ScheduleUtils.removeJob(scheduler, job.getJobId(), job.getJobGroup());
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            });
        }
        return removeByIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public boolean start(SysJob sysJob) {
        if (sysJob != null) {
            if (updateById(sysJob)) {
                if (sysJob.getStatus().equals(ScheduleConstants.Status.NORMAL.getValue())) {
                    try {
                        ScheduleUtils.createScheduleJob(scheduler, sysJob);
                    } catch (SchedulerException e) {
                        System.out.println(e.getMessage());
                        e.printStackTrace();
                        throw new RuntimeException();
                    }
                } else {
                    try {
                        ScheduleUtils.removeJob(scheduler, sysJob.getJobId(), sysJob.getJobGroup());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                        e.printStackTrace();
                        throw new RuntimeException();
                    }
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public void run(SysJob sysJob) {
        try {
            ScheduleUtils.runOneJob(scheduler, sysJob);
        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new TaskException("定时任务执行错误", TaskException.Code.TASK_EXISTS, e);
        }
    }
}
